AJAX auto-completion
We can further spruce up our search field by offering auto-completion
of its contents. This feature will allow users to type the beginning of
a search term and be presented with all of the possible terms that
begin with the typed string. Since the list of terms can be drawn from
a database that is driving the site, the user can know that search
results are forthcoming if the typed term is used. Also, if the
database provides the terms in order of popularity or number of
results, the user can be guided to more appropriate searches.
Auto-completion is a very
complicated subject with subtleties introduced by different kinds of
user interaction. We will craft a working example here, but cannot, in
this space, explore all of the advanced concepts such as limiting the
rate of requests or multi-term completion. The auto-complete widget in
the jQuery UI
plugin collection is recommended for simple, real-world
implementations, and as a starting point for more complex ones. It can
be found at http://ui.jquery.com/.
The basic idea behind an
auto-completion routine is to react to a keystroke, and to send an AJAX
request to the server containing the contents of the field in the
request. The results will contain a list of possible completions for
the field. The script then presents this list as a dropdown below the
field.
On the server
We need some server-side
code to handle requests. While a real-world implementation will usually
rely on a database to produce a list of possible completions, for this
example we can use a simple PHP script with the results built in:
<?php
if (strlen($_REQUEST['search-text']) < 1) {
print '[]';
exit;
}
$terms = array(
'access',
'action',
// List continues...
'xaml',
'xoops',
);
$possibilities = array();
foreach ($terms as $term) {
if (strpos($term, strtolower($_REQUEST['search-text']))
=== 0) {
$possibilities[] = "'". str_replace("'", "\\'", $term)
."'";
}
}
print ('['. implode(', ', $possibilities) .']');
The page compares the provided string against the beginning of each term, and composes a JSON array of matches. The string manipulation operations here (such as and implode()) ensure that the output of the script is properly-formatted JSON, so as to avoid JavaScript errors during parsing. str_replace()